package io.gitee.welson.sensitive.condition;

import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.util.StringUtils;

/**
 * 条件表达式处理器
 * 用于处理@SensitiveField注解中的condition表达式
 *
 * @author welson
 */
public class ConditionEvaluator {
    private final ExpressionParser parser = new SpelExpressionParser();
    private final BeanFactoryResolver beanFactoryResolver;

    public ConditionEvaluator(BeanFactoryResolver beanFactoryResolver) {
        this.beanFactoryResolver = beanFactoryResolver;
    }

    /**
     * 评估条件表达式
     *
     * @param condition 条件表达式
     * @return 表达式的评估结果，如果表达式为空则返回true
     */
    public boolean evaluate(String condition) {
        if (!StringUtils.hasText(condition)) {
            return true;
        }

        try {
            Expression expression = parser.parseExpression(condition);
            StandardEvaluationContext context = new StandardEvaluationContext();
            context.setBeanResolver(beanFactoryResolver);
            return Boolean.TRUE.equals(expression.getValue(context, Boolean.class));
        } catch (Exception e) {
            // 如果表达式评估出错，记录日志并返回true（保守处理，出错时进行脱敏）
            return true;
        }
    }

    /**
     * 评估表达式并返回结果
     */
    public Object evaluateExpression(String expression) {
        if (!StringUtils.hasText(expression)) {
            return null;
        }

        try {
            Expression parsedExpression = parser.parseExpression(expression);
            StandardEvaluationContext context = new StandardEvaluationContext();
            context.setBeanResolver(beanFactoryResolver);
            return parsedExpression.getValue(context);
        } catch (Exception e) {
            return null;
        }
    }
} 